<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/17 23:20
 */

namespace module\user\front\input;

use app\library\validate\CaptchaValidate;
use mof\exception\LogicException;
use mof\Request;


/**
 * 登录输入
 * @property string $type 登录类型
 * @property string $username 用户名
 * @property string $password 密码
 * @property string $mobile 手机号
 * @property string $captcha 验证码
 */
class LoginInput
{
    const TYPE_PASSWORD = 'password';
    const TYPE_SMS      = 'sms';

    protected array $attrs = [
        'type', 'username', 'password', 'mobile', 'invite'
    ];

    public function __construct(protected array $data)
    {
    }

    public static function __make(Request $request): static
    {
        $type = $request->post('type', static::TYPE_PASSWORD);
        if ('password' === $type) {
            $rules = [
                'username' => 'require',
                'password' => 'require|min:5',
                'captcha'  => 'require|imgCaptcha',
            ];
            $message = [
                'username.require'   => '用户名不能为空',
                'password.require'   => '密码不能为空',
                'password.min'       => '密码不能少于5个字符',
                'captcha.require'    => '验证码不能为空',
                'captcha.imgCaptcha' => '验证码不正确',
            ];
        } else if ('sms' === $type) {
            $rules = [
                'mobile'  => 'require|mobile',
                'captcha' => 'require|number|smsCaptcha:mobile,#login',
            ];
            $message = [
                'mobile.require'     => '手机号不能为空',
                'mobile.mobile'      => '手机号格式不正确',
                'captcha.require'    => '验证码不能为空',
                'captcha.number'     => '验证码格式错误',
                'captcha.smsCaptcha' => '验证码不正确',
            ];
        } else {
            throw new LogicException('未知登录类型');
        }

        CaptchaValidate::register();
        $data = $request->withValidate($rules, $message)->post();

        return new self($data);
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }

}